import { getMerchantApi } from "@/api/common"
import { findArrayItem } from "./tree"
import _ from "lodash"

// 获取URL全部参数 ， 返回一个对象
export function getUrlAllParameters() {
  const url = decodeURI(window.location.href)
  const result = {}
  const url_data = _.split(url, "?").length > 1 ? _.split(url, "?")[1] : null
  if (!url_data) return {}
  const parameters_array = _.split(url_data, "&")
  for (const item of parameters_array) {
    const key = _.split(item, "=")[0]
    const value = _.split(item, "=")[1]
    result[key] = value
  }
  return result
}

export const setFavicon = async () => {
  try {
    await getMerchantApi()
  } catch (error) {
    // 因为用的统一API拦截方法，这里返回的code 跟费控的code 不一致，所以只能在catch 中拦截 获取响应结果
    const platFromLogoUrl = error?.data?.platFromLogoUrl
    const link = document.createElement("link")
    link.setAttribute("rel", "shortcut icon")
    link.setAttribute("type", "image/x-icon")
    link.href = platFromLogoUrl
    document.head.append(link)
  }
}

/**
* @description: 设置options的数据 根据用户传入的 fields 进行映射
* @param { Array } options
* @param { Object } fields
*/
export const setOptionsFiled = (options, fields) => {
  if (!fields) return new Error("请传入fields字段")
  findArrayItem(options, item => {
    for (const key in item) {
      if (fields[key]) item[fields[key]] = item[key]
    }
  })
}

/**
* @description: 把field字段映射城对象
* @param { String } field
* @return { Record<string,string> }
*/
export const filedToObject = (field) => {
  if (!field) return ""
  const fields = field.split(",")
  const conversionResultKey = {}
  for (const item of fields) {
    const [oldKey, newKey] = item.split("as")
    conversionResultKey[oldKey.trim()] = newKey.trim()
  }
  return conversionResultKey
}